package com.my.goodsmanage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.goodsmanage.entity.*;
import com.my.goodsmanage.entity.form.Rtable;
import com.my.goodsmanage.enums.PictureEnum;
import com.my.goodsmanage.service.PictureService;
import com.sun.net.httpserver.HttpsConfigurator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @author 徐佳辉
 * @date 2020/9/24 18:43
 */
@RestController
@RequestMapping("/pic")
@Slf4j
public class PictureController {

    @Value("${picture.url}")
    private String url;

    @Autowired
    private PictureService pictureService;

    /**
     * 先上传到数据库
     * 再传到硬盘上，在使用事务
     *
     * @param goodId
     * @param multipartFile
     * @return {
     * "code": 0
     * ,"msg": ""
     * ,"data": {
     * "src": "http://cdn.layui.com/123.jpg"
     * }
     * }
     */
    @PostMapping("/upload")
    @Transactional
    public Result uploadPic(@RequestParam Integer goodId, @RequestParam("file") MultipartFile multipartFile, HttpSession session) throws IOException {
        log.info("上传");
        log.info("goodid:{}", goodId);
        Result r = new Result();
        User user = (User) session.getAttribute("user");

        if (multipartFile.isEmpty()) {
            r.setCode(1);
            r.setMsg("文件为空");
            return r;
        }
        String fileName = multipartFile.getOriginalFilename();
        // 后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 新文件名
        fileName = UUID.randomUUID() + suffixName;
        File dest = new File(url + fileName);
        log.info("上传的文件:【{}】", dest);

        //传到磁盘
        boolean picturToDisk = uploadPicturToDisk(multipartFile, dest, goodId);
        //传到数据库
        boolean b = pictureService.uploadPicture(fileName, goodId, user.getUserId());

        if (picturToDisk) {
            r.setCode(PictureEnum.SUCCESS.getCode());
            r.setMsg(PictureEnum.SUCCESS.getMsg());
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("src","/imgs/"+fileName);
            r.setData(hashMap);
            return r;
        } else {
            r.setCode(PictureEnum.OUT_OF_DISK_SPACE.getCode());
            r.setMsg(PictureEnum.OUT_OF_DISK_SPACE.getMsg());
            return r;
        }


    }

    private boolean uploadPicturToDisk(MultipartFile multipartFile, File file, int goodId) throws IOException {

        //todo 如果原来存在删除
        QueryWrapper<Picture> wrapper = new QueryWrapper<>();
        wrapper.eq("good_id", goodId);
        Picture one = pictureService.getOne(wrapper);
        if (one != null) {
            String address = one.getAddress();
            int lastIndexOf = address.lastIndexOf("/");
            String substring = address.substring(lastIndexOf + 1);
            log.info("uploadPicturToDisk====substring:[{}]", substring);
            String path = url + substring;
            log.info("uploadPicturToDisk====path:[{}]", path);
            boolean deleteFile = deleteFile(path);
            log.info("uploadPicturToDisk====deleteFile:[{}]", deleteFile);
            multipartFile.transferTo(file);
            return true;
        }

        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        multipartFile.transferTo(file);
        return true;

    }

    public boolean deleteFileOnTwo(int goodId) {
        QueryWrapper<Picture> wrapper = new QueryWrapper<>();
        wrapper.eq("good_id", goodId);
        Picture one = pictureService.getOne(wrapper);
        if (one == null) {
            return true;
        }
        String address = one.getAddress();
        int lastIndexOf = address.lastIndexOf("/");
        String substring = address.substring(lastIndexOf + 1);

        log.info("substring:[{}]", substring);
        String path = url + substring;
        log.info("path:[{}]", path);
        boolean deleteFile = deleteFile(path);
        if (deleteFile) {
            boolean removeById = pictureService.remove(wrapper);
            if (removeById) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    private boolean deleteFile(String path) {
        boolean flag = false;
        File file = new File(path);
        // 路径为文件且不为空则进行删除
        log.info("file:【{}】", file.toString());
        log.info("path:【{}】", path);
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    @PostMapping("/page")
    public PageR picList(@RequestParam int page, @RequestParam int limit, HttpSession session, String name) {
        User user = (User) session.getAttribute("user");
        PageR r = new PageR();

        Page<PictureDto> pictureDtoPage = new Page<>(page, limit);
        List<PictureDto> pictureDtos = pictureService.pageListCondition(pictureDtoPage, user.getUserId(), name);
        r.setCode(0);
        r.setCount(pictureDtoPage.getTotal());
        r.setSuccess(true);
        r.setMsg("成功");
        r.setData(pictureDtos);
        return r;
    }

    @PostMapping("/delete/{goodId}")
    public R deletePic(@PathVariable Integer goodId) {
        log.info("goodId:[{}]", goodId);


        QueryWrapper<Picture> wrapper = new QueryWrapper<>();
        wrapper.eq("good_id", goodId);
        Picture one = pictureService.getOne(wrapper);
        if (one==null){
            return R.error("无图片");
        }
        String address = one.getAddress();
        int lastIndexOf = address.lastIndexOf("/");
        String substring = address.substring(lastIndexOf + 1);

        log.info("substring:[{}]", substring);
        String path = url + substring;
        log.info("path:[{}]", path);
        boolean deleteFile = deleteFile(path);
        log.info("deleteFile:[{}]", deleteFile);
        if (deleteFile) {
            boolean removeById = pictureService.remove(wrapper);
            if (removeById) {
                return R.success("删除成功");
            } else {
                return R.error("删除数据失败");
            }
        } else {
            boolean removeById = pictureService.remove(wrapper);
            if (removeById) {
                return R.success("删除数据成功");
            }
            return R.error("删除失败");
        }


    }


}
